import BySpace from "../ui/BySpace";
import ByTag from "../ui/ByTag";

type TagRadioGroupProps = {
  options: { [property: string]: any }[];

  limit?: number;
  value?: any[];

  labelKey?: string;
  valueKey?: string;

  onChange?: (res: any[], item: TagRadioGroupProps["options"][number]) => void;
};

export default ({
  limit = 1,
  options = [],
  value = [],

  labelKey = "label",
  valueKey = "label",

  onChange,
}: TagRadioGroupProps) => {
  const handleClick = (item: TagRadioGroupProps["options"][number]) => {
    const val = item[valueKey];

    if (limit === 1) {
      onChange?.([val], item);
    } else {
      const checkedIndex = value.findIndex((e) => e === val);

      if (checkedIndex > -1) {
        value.splice(checkedIndex, 1);
      } else {
        value.push(val);
      }

      onChange?.(value, item);
    }
  };

  return (
    <BySpace>
      {options.map((item, index) => (
        <ByTag
          key={index}
          size="small"
          type={value.includes(item[valueKey]) ? "primary" : "info"}
          variant={value.includes(item[valueKey]) ? "filled" : "outline"}
          onClick={() => handleClick(item)}
        >
          {item[labelKey]}
        </ByTag>
      ))}
    </BySpace>
  );
};
